<template>
  <div class="withdraw-action">
    <Form style="margin-top: 20px;">
      <CellGroup inset>
        <Field v-model="config.alipayAccount"
          is-link readonly clickable
          name="alipayAccount" label="账户"
          placeholder="请选择账户"
          @click="pageState.showPicker = true" />

        <Field v-model="config.amount"
          name="amount" label="金额" readonly
          clickable
          @touchstart.stop="pageState.showNumberKeyBoard = true"
          placeholder="请输入金额" autocomplete="off"
          :rules="[{ required: true, message: '请输入金额' }]">
          <template #right-icon>
            <Tag type="primary">元</Tag>
          </template>
        </Field>
        <NumberKeyboard v-model="config.amount"
          :show="pageState.showNumberKeyBoard"
          @blur="pageState.showNumberKeyBoard = false"
          :maxlength="6" />
      </CellGroup>
    </Form>

    <div class="btn">
      <Button @click="handleSubmit" type="primary"
        v-if="accountList.data.length"
        :loading="pageState.loading || accountList.loading"
        class="confirm" block>提交</Button>

      <Button
        @click="$router.replace({ name: 'WithdrawAccount' })"
        v-if="!accountList.data.length"
        type="primary" class="confirm"
        block>前往添加提现账号</Button>
    </div>

    <Popup v-model:show="pageState.showPicker"
      :style="{ height: '40%' }" round
      position="bottom"
      @click-close-icon="pageState.showPicker = false">
      <Picker
        :columns="accountList.data
          .map((item) => ({ text: item.account, value: item.id }))"
        @cancel="pageState.showPicker = false"
        @confirm="onConfirmPicker" />
    </Popup>
  </div>
</template>
<script setup lang="ts">
import {
  Button,
  CellGroup, Field, Form, NumberKeyboard, Picker, Popup, Tag,
} from 'vant';
import { onMounted } from 'vue';

import useWithdrawAccount from '../hooks/useWithdrawAccount';
import useWithdrawAction from '../hooks/useWithdrawAction';

const { state: accountList, fetchData: fetchAccounts } = useWithdrawAccount();
const { pageState, config, fetchData: handleSubmit } = useWithdrawAction();

onMounted(async () => {
  await fetchAccounts();
});

interface ISelectedFaceValue { _: number[], selectedOptions: any[] }

const onConfirmPicker = (
  {
    selectedOptions,
  }: ISelectedFaceValue,
) => {
  config.value.alipayAccount = selectedOptions[0].text;
  config.value.withdrawalAccountId = selectedOptions[0].value;
  pageState.value.showPicker = false;
};
</script>
<style lang="less" scoped>
.withdraw-action {
  height: 100%;
  display: flex;
  flex-direction: column;

  .btn {
    flex-grow: 1;
    display: flex;
    justify-content: center;
    flex-direction: column;
    padding: 16px;

    .confirm {
      margin-bottom: auto;
    }
  }
}
</style>
